package com.itheima.travel.service.impl;

import com.itheima.travel.mapper.AffixMapper;
import com.itheima.travel.pojo.Affix;
import com.itheima.travel.pojo.AffixExample;
import com.itheima.travel.req.AffixVo;
import com.itheima.travel.service.AffixService;
import com.itheima.travel.utils.BeanConv;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.List;
import java.util.UUID;

/**
 *
 */
@Service
public class AffixServiceImpl implements AffixService {
    @Autowired
    private AffixMapper affixMapper;

    @Value("${upload.pathRoot}")
    String pathRoot;
    @Override
    public AffixVo upLoad(MultipartFile multipartFile, AffixVo affixVo) throws IOException {
        // 判断文件是否为空
        if (multipartFile==null){
            return null;
        }
        // 获取文件夹名
        String businessType = affixVo.getBusinessType();
        // 原始上传的文件名称
        String originalFilename = multipartFile.getOriginalFilename();
        // 获取后缀名称
        String suffix = originalFilename.substring(originalFilename.lastIndexOf("."));
        affixVo.setSuffix(suffix);
        // 文件名称
        String fileName = UUID.randomUUID().toString();
        affixVo.setFileName(fileName);
        // 构建访问路径
        String pathUrl = businessType + "/" + fileName + suffix;
        // 判断业务类型的文件夹是否存在
        File file = new File(pathRoot + businessType);
        if (!file.exists()){
            file.mkdir();
        }
        file = new File(pathRoot + "/" + pathUrl);
        // 上传文件
        multipartFile.transferTo(file);
        affixVo.setPathUrl(pathUrl);
        Affix affix = BeanConv.toBean(affixVo, Affix.class);
        affixMapper.insert(affix);
        return BeanConv.toBean(affix,AffixVo.class);
    }

    @Override
    // 将图片绑定到线路上
    public Boolean bindBusinessId(AffixVo affixVo) {
        Affix affix = BeanConv.toBean(affixVo, Affix.class);
        int flag = affixMapper.updateByPrimaryKeySelective(affix);
        return flag>0;
    }

    @Override
    // 根据业务id查询附件
    public List<AffixVo> findAffixByBusinessId(AffixVo affixVo) {
        AffixExample example = new AffixExample();
        example.createCriteria()
                .andBusinessIdEqualTo(affixVo.getBusinessId());
        List<Affix> affixes = affixMapper.selectByExample(example);
        return BeanConv.toBeanList(affixes,AffixVo.class);
    }
}
